<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="type" label="页面">
        <uni-data-checkbox v-model="formData.type" :localdata="formOptions.type_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="name" label="配置名称">
        <uni-easyinput placeholder="配置名称" v-model="formData.name"></uni-easyinput>
      </uni-forms-item>
	  <uni-forms-item name="sign" label="配置标识">
	    <uni-easyinput placeholder="标识" v-model="formData.sign"></uni-easyinput>
	  </uni-forms-item>
	  <button type="primary" class="uni-button" style="width: 100px;" @click="add">新增</button>
	  <view v-for="(item,index) in formData.content"  :key="item.id" class="flex-content-column">
		  <view class="flex-content">
		  	<uni-forms-item :name="['content',index,'name']" :label="'配置名称'+(index+1)">
		  							<uni-easyinput placeholder="配置名称" v-model="formData.content[index].name"></uni-easyinput>
		  	</uni-forms-item>
		  	<view style="width: 20px;">
		  	</view>
		  	<uni-forms-item :name="['content',index,'value']" :label="'配置内容'+(index+1)">
		  	      		<uni-easyinput placeholder="配置内容" v-model="formData.content[index].value"></uni-easyinput>
		  	</uni-forms-item>
		  	<view style="width: 20px;">
		  	</view>
		  </view>
		 
		  <view class="flex-content">
			  <uni-forms-item :name="['content',index,'icon']" :label="'配置图标'+(index+1)">
					<view  class="item-flex">
							<uni-easyinput v-model="formData.content[index].icon" :clearable="false" placeholder="请输入配置图标css样式类名">
								<template v-slot:right>
									<span style="color: #007aff; cursor: pointer;padding-right: 10px;" @click="showIconPopup">内置图标</span>
								</template>
							</uni-easyinput>
								<button  class="uni-button" style="width: 100px;" @click="del(item.id)">删除</button>
						</view>
			  </uni-forms-item>
		  </view>
	  </view>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
	<uni-popup class="icon-modal-box" ref="iconPopup" type="center">
		<view class="icon-modal icon-modal-pc">
			<Icons :tag="false" :fix-window="false"/>
		</view>
	</uni-popup>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-page-configs.js';
  import Icons from '@/pages/demo/icons/icons.vue'

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-page-configs';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "type": 1,
        "name": "",
		"sign":"",
        "content": []
      }
      return {
        formData,
        formOptions: {
          "type_localdata": [
            {
              "text": "首页",
              "value": 1
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    components: {
    	Icons
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
    	add(){
    		this.formData.content.push({
    			name:'',
    			icon:'',
				value:'',
				id:new Date().getTime()
    		})
    	},
		// 删除表单域
		del(id) {
			let index = this.formData.content.findIndex(v => v.id === id)
			this.formData.content.splice(index, 1)
		},
      showIconPopup() {
      	this.$refs.iconPopup.open()
      },
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
<style scoped>
	.icon-modal-box {
		padding-top: var(--top-window-height);
	}
	
	.icon-modal {
		width: 350px;
		background-color: #fff;
		height: 500px;
		overflow-y: scroll;
	}
	
	@media screen and (min-width: 768px) {
		.icon-modal-pc {
			width: 600px;
		}
	}
	
	::v-deep .uni-forms-item__label {
		width: 90px !important;
	}
	.flex-content{
		display: flex;
		margin-bottom: 10rpx;
	}
	.flex-content-column{
		display: flex;
		flex-direction: column;
	}
	.item-flex{
		display: flex;
		margin-bottom: 10rpx;
	}
</style>
